package com.ruoyi.location.repository;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.location.repository.dao.TeamDao;
import com.ruoyi.location.repository.generator.entity.*;
import com.ruoyi.location.repository.generator.mapper.*;
import com.ruoyi.location.vo.req.TeamCreateReq;
import com.ruoyi.location.vo.req.TeamUpdateReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Repository
public class TeamRepository {
    @Autowired
    private LocationTeamMapper locationTeamMapper;
    @Autowired
    private LocationRelationUserTeamMapper locationRelationUserTeamMapper;
    @Autowired
    private LocationInviteCodeMapper locationInviteCodeMapper;
    @Autowired
    private LocationReportRecordMapper locationReportRecordMapper;
    @Autowired
    private TeamDao teamDao;
    @Autowired
    private LocationUserInfoMapper locationUserInfoMapper;

    public List<LocationTeam> listTeamByUserId() {
        SysUser user = ShiroUtils.getSysUser();
        Long userId = user.getUserId();
        // 1. 查询用户关联的team
        LocationRelationUserTeamExample relationExample = new LocationRelationUserTeamExample();
        relationExample.createCriteria().andUserIdEqualTo(userId);
        List<LocationRelationUserTeam> relations = locationRelationUserTeamMapper.selectByExample(relationExample);

        if (relations.isEmpty()) {
            return new ArrayList<>();
        }

        // 2. 获取teamId列表
        List<Long> teamIds = relations.stream()
                .map(LocationRelationUserTeam::getTeamId)
                .collect(Collectors.toList());

        // 3. 查询team信息
        LocationTeamExample teamExample = new LocationTeamExample();
        teamExample.createCriteria().andIdIn(teamIds)
                .andValidEqualTo(1);
        return locationTeamMapper.selectByExample(teamExample);
    }

    public LocationTeam create(TeamCreateReq req) {
        LocationTeam team = new LocationTeam();
        team.setName(req.getName());
        team.setOwnerId(ShiroUtils.getUserId());
        team.setValid(1);
        locationTeamMapper.insertSelective(team);
        return team;
    }

    public void relationUserTeam(Long userId, Long teamId) {
        LocationRelationUserTeamExample e = new LocationRelationUserTeamExample();
        e.createCriteria().andUserIdEqualTo(userId).andTeamIdEqualTo(teamId);
        List<LocationRelationUserTeam> rel = locationRelationUserTeamMapper.selectByExample(e);
        if (CollectionUtils.isEmpty(rel)) {
            LocationRelationUserTeam ut = new LocationRelationUserTeam();
            ut.setUserId(userId);
            ut.setTeamId(teamId);
            locationRelationUserTeamMapper.insertSelective(ut);
        }
    }

    public LocationTeam update(TeamUpdateReq req) {
        LocationTeam team = new LocationTeam();
        team.setId(req.getId());
        team.setName(req.getName());
        locationTeamMapper.updateByPrimaryKeySelective(team);
        return locationTeamMapper.selectByPrimaryKey(req.getId());
    }

    public void deleteTeam(Long teamId) {
        LocationTeam team = new LocationTeam();
        team.setId(teamId);
        team.setValid(0);
        locationTeamMapper.updateByPrimaryKeySelective(team);

        LocationRelationUserTeamExample e2 = new LocationRelationUserTeamExample();
        e2.createCriteria().andTeamIdEqualTo(teamId);
        locationRelationUserTeamMapper.deleteByExample(e2);
    }

    public void quitTeam(Long userId, Long teamId) {
        LocationRelationUserTeamExample e2 = new LocationRelationUserTeamExample();
        e2.createCriteria().andUserIdEqualTo(userId).andTeamIdEqualTo(teamId);
        locationRelationUserTeamMapper.deleteByExample(e2);
    }

    public void insertRelUserTeam(Long userId, Long teamId) {
        LocationRelationUserTeam ut = new LocationRelationUserTeam();
        ut.setUserId(userId);
        ut.setTeamId(teamId);
        locationRelationUserTeamMapper.insertSelective(ut);
    }

    public LocationInviteCode insertInvite(String code, Long teamId, Long inviterId) {
        LocationInviteCode invite = new LocationInviteCode();
        invite.setCode(code);
        invite.setTeamId(teamId);
        invite.setInviterId(inviterId);
        locationInviteCodeMapper.insertSelective(invite);
        return invite;

    }
    public List<LocationUserInfo> listUserByTeamId(Long teamId) {
        // 1. 查询团队下的所有用户ID
        LocationRelationUserTeamExample relationExample = new LocationRelationUserTeamExample();
        relationExample.createCriteria().andTeamIdEqualTo(teamId);
        List<LocationRelationUserTeam> relations = locationRelationUserTeamMapper.selectByExample(relationExample);

        if (CollectionUtils.isEmpty(relations)) {
            return Collections.emptyList();
        }

        // 2. 获取用户ID列表
        List<Long> userIds = relations.stream()
                .map(LocationRelationUserTeam::getUserId)
                .collect(Collectors.toList());
        // 3. 根据用户ID查询用户信息
        LocationUserInfoExample e = new LocationUserInfoExample();
        e.createCriteria().andUserIdIn(userIds);
        List<LocationUserInfo> users = locationUserInfoMapper.selectByExample(e);
        return users;
    }

    public List<LocationReportRecord> listLatestLocationByTeamId(List<Long> userIds) {
        // 3. 查询每个用户的最新位置记录
        List<LocationReportRecord> result = new ArrayList<>();
        for (Long userId : userIds) {
            // 使用selectByExample方法，然后在代码中限制结果数量
            LocationReportRecord record = teamDao.selectLatestByUserId(userId);
            
            if (record != null) {
                // 只取第一条记录（最新的）
                result.add(record);
            }
        }
        return result;
    }

    public LocationReportRecord selectLatestByUserId(Long userId) {
        return teamDao.selectLatestByUserId(userId);
    }
}
